

package top.continew.admin.rpc;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import top.continew.admin.question.dify.workflow.QuestionWorkflow;
import top.continew.admin.question.manger.service.MangerQuestionService;
import top.continew.admin.question.manger.service.model.PointVO;
import top.continew.admin.question.manger.service.model.SaveQuestion;
import top.continew.admin.question.model.question.QuestionSet;
import top.continew.admin.question.user.service.questionset.entity.AbstractQuestionSet;
import top.continew.admin.question.user.service.questionset.entity.SpecialPracticeQuestionSet;
import top.continew.admin.question.user.service.questionset.enums.QuestionSetTypeEnum;
import top.continew.admin.question.user.service.questionset.factory.QuestionSetFactory;
import top.continew.admin.question.dify.workflow.req.QuestionGenerateReq;
import com.shengchao.examstar.rpc.question.api.ISpecialPracticeRpc;
import com.shengchao.examstar.rpc.question.req.SpecialPracticeGenerateReq;
import com.shengchao.examstar.rpc.question.resp.SpecialPracticeResp;
import com.shengchao.examstar.rpc.question.resp.SpecialPracticeIdsResp;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 专项练习RPC接口实现
 * 提供专项练习的生成、管理等功能
 */
@Slf4j
@DubboService
public class SpecialPracticeRpc implements ISpecialPracticeRpc {

    @Autowired
    private MangerQuestionService mangerQuestionService;

    /**
     * 生成专项练习
     * 1. 调用Dify生成题目
     * 2. 生成专项练习题集
     * 3. 把题目关联到题集
     *
     * @param request 专项练习生成请求
     * @return 专项练习响应信息
     */
    @Override
    public SpecialPracticeResp generateSpecialPractice(SpecialPracticeGenerateReq request) {
        SpecialPracticeResp response = new SpecialPracticeResp();

        try {
            log.info("开始生成专项练习，用户ID: {}, 标题: {}, 知识点: {}, 题目数量: {}", request.getUserId(), request.getTitle(), request
                .getKnowledge(), request.getSum());

            // 1. 调用Dify生成题目
            QuestionGenerateReq generateReq = new QuestionGenerateReq();
            generateReq.setKnowledge(request.getKnowledge());
            generateReq.setType(request.getType());
            generateReq.setSum(request.getSum());
            generateReq.setQuestionType(request.getQuestionType());
            generateReq.setSummary(request.getSummary());
            List<SaveQuestion> generatedQuestions = QuestionWorkflow.questionGenerateWorkflow(generateReq);

            if (generatedQuestions == null || generatedQuestions.isEmpty()) {
                response.setStatus("FAILED");
                response.setErrorMessage("Dify工作流未生成任何题目");
                return response;
            }

            log.info("Dify工作流生成题目数量: {}", generatedQuestions.size());

            // 2. 生成专项练习题集
            SpecialPracticeQuestionSet specialPracticeQuestionSet = (SpecialPracticeQuestionSet)QuestionSetFactory
                .of(Map.of("userId", request.getUserId(), "knowledgeId", request.getKnowledgeId() != null
                    ? request.getKnowledgeId()
                    : request.getSpecificationTypeId()), QuestionSetTypeEnum.SPECIAL_PRACTICE.getCode());
            QuestionSet questionSet = specialPracticeQuestionSet.getQuestionSet();

            Long questionSetId = questionSet.getId();
            log.info("创建专项练习题集成功，题集ID: {}", questionSetId);
            specialPracticeQuestionSet.clearQuestion();

            // 3. 保存生成的题目并关联到题集
            List<Long> questionIds = new ArrayList<>();

            for (SaveQuestion saveQuestion : generatedQuestions) {
                try {
                    // 设置题目类目
                    if (request.getSpecificationTypeId() == null) {
                        saveQuestion.setSubjectId(1L); // 默认学科ID
                    } else {
                        saveQuestion.setSubjectId(request.getSpecificationTypeId());
                    }
                    if (StrUtil.isNotEmpty(saveQuestion.getAnswer()) && !saveQuestion.getAnswer().contains("[")) {
                        saveQuestion.setAnswer("[\"" + saveQuestion.getAnswer() + "\"]");
                    }
                    saveQuestion.setIsAi(1L);
                    saveQuestion.setOnlineStatus(1L);
                    if (request.getKnowledgeId() != null) {
                        List<PointVO> pointVOS = new ArrayList<>();
                        PointVO pointVO = new PointVO();
                        pointVO.setPointId(request.getKnowledgeId());
                        pointVO.setName(request.getKnowledge());
                        pointVOS.add(pointVO);
                        saveQuestion.setKnowledgePoints(pointVOS);
                    }
                    // 保存题目
                    SaveQuestion savedQuestion = mangerQuestionService.save(saveQuestion);
                    Long questionId = savedQuestion.getId();
                    questionIds.add(questionId);

                    // 将题目关联到题集
                    specialPracticeQuestionSet.addQuestion(questionSetId, questionId, request.getUserId(), "专项练习生成");

                    // 处理子题目（如果存在）
                    if (saveQuestion.getSubQuestions() != null && !saveQuestion.getSubQuestions().isEmpty()) {
                        for (SaveQuestion subQuestion : saveQuestion.getSubQuestions()) {
                            subQuestion.setParentId(questionId);
                            subQuestion.setSubjectId(saveQuestion.getSubjectId());

                            SaveQuestion savedSubQuestion = mangerQuestionService.save(subQuestion);
                            Long subQuestionId = savedSubQuestion.getId();
                            questionIds.add(subQuestionId);

                            // 将子题目也关联到题集
                            specialPracticeQuestionSet.addQuestion(questionSetId, subQuestionId, request
                                .getUserId(), "专项练习生成-子题目");
                        }
                    }

                    log.info("题目保存成功，题目ID: {}", questionId);

                } catch (Exception e) {
                    log.error("保存题目失败: {}", e.getMessage(), e);
                    // 继续处理其他题目，不中断整个流程
                }
            }

            // 4. 构建响应信息
            response.setPracticeId(questionSetId);
            response.setTitle(request.getTitle());
            response.setUserId(request.getUserId());
            response.setKnowledge(request.getKnowledge());
            response.setType(request.getType());
            response.setQuestionCount(questionIds.size());
            response.setQuestionType(request.getQuestionType());
            response.setDifficultyLevel(request.getDifficultyLevel());
            response.setDescription(request.getDescription());
            response.setCreateTime(new Date());
            response.setQuestionIds(questionIds);
            response.setStatus("SUCCESS");

            log.info("专项练习生成成功，题集ID: {}, 题目数量: {}", questionSetId, questionIds.size());

        } catch (Exception e) {
            log.error("生成专项练习失败: {}", e.getMessage(), e);
            response.setStatus("FAILED");
            response.setErrorMessage("生成专项练习失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 根据知识点ID和用户ID获取专项练习题集ID列表
     *
     * @param knowledgeId 知识点ID
     * @param userId      用户ID
     * @return 专项练习题集ID列表响应
     */
    @Override
    public SpecialPracticeIdsResp getSpecialPracticeIdsByKnowledge(Long knowledgeId, Long userId) {
        SpecialPracticeIdsResp response = new SpecialPracticeIdsResp();

        try {
            log.info("开始查询专项练习题集，知识点ID: {}, 用户ID: {}", knowledgeId, userId);

            // 查询用户的所有专项练习题集
            AbstractQuestionSet questionSets = QuestionSetFactory.of(Map
                .of("userId", userId, "knowledgeId", knowledgeId), QuestionSetTypeEnum.SPECIAL_PRACTICE.getCode());

            if (questionSets == null) {
                log.info("未找到用户的专项练习题集，用户ID: {}", userId);
                response.setStatus("SUCCESS");
                response.setHasPractice(false);
                return response;
            }
            // 构建响应信息
            response.setHasPractice(true);
            response.setQuestionSetId(questionSets.getQuestionSet().getId());
            response.setStatus("SUCCESS");

        } catch (Exception e) {
            log.error("查询专项练习题集失败: {}", e.getMessage(), e);
            response.setStatus("FAILED");
            response.setErrorMessage("查询专项练习题集失败: " + e.getMessage());
        }

        return response;
    }

}